package com.lids.test;


import io.netty.buffer.ByteBuf;
import org.jboss.marshalling.Marshaller;

import java.io.IOException;

/**
 * @Des
 * @Date: 2021/1/11 12:32
 */
public class MarshallingEncoder {
    private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
    Marshaller marshaller;

    public MarshallingEncoder() throws IOException {
           marshaller = MarshallingCodecFactory.buildMarshalling();
    }

    /**
     *  marshaller 进行msg编码
     * @param msg
     * @param out
     * @throws Exception
     */
    protected void encoder(Object msg, ByteBuf out) throws Exception{
        try {
            int lengthPos = out.writerIndex();
            out.writeBytes(LENGTH_PLACEHOLDER);
            ChannelBufferByteOutput  output = new ChannelBufferByteOutput(out);
            marshaller.start(output);
            marshaller.writeObject(msg);
            marshaller.finish();
            //在指定位置写入数据，写入数据的长度，为了获取数据使用
            out.setInt(lengthPos,out.writerIndex()-lengthPos-4);
        }finally {
           marshaller.close();
        }
    }

}
